package com.memoryangelapplication;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.memoryangelapplication.services.EventAlarm;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.view.GestureDetector;

public class AlertMessagePreviewAdapter extends PagerAdapter {
	
	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "memoryangel.db";
	private String MEM_EVENT = "table_events";
	private static final String TAG = null;
	String DateSendAct, TimeAct, Tzone;
	long TimeStampValue;
	long nextReminderTimeStamp;
	int counter = 0;
	private ViewPager viewPager;
	// Declare Variables
	Context context;
	String[] title;
	String[] description;
	String[] reminder_date;
	String[] event_count_flag;
	
	//Handling Variables
	String[] event_id; // Index(0)
	String[] event_alam_time; // Index(8)
	String[] event_url; // Index(11)
	String[] event_package; // Index(12)
	String[] event_ack_count; // Index(15)
	String[] eventReminderTime; // Index(16)
	String[] eventReminderNumber; // Index(17)
	String[] eventWaitTime; // Index(18)
	String[] eventNotifyType; // Index(19)
	
	//Calculate Variables
	int eventwaittimePeriod = 0;
	int wait_time = 0;
	int reminder_number = 0;
	int event_reminder_time = 0;
	int eventTTS = 0;
	int eventContPlay = 0;
	int eventSoundGap = 0;
	int recordCount = 0;
	String evtDes;
	String updateEventId;
	String eventURL;
	String eventPackage;
	int readIndex = 0;
	
	ScheduledThreadPoolExecutor executor;
	ScheduledThreadPoolExecutor executor1;
	Handler handler, main_handelr;
	SoundManager soundManager;
	SoundManager1 soundManager1;
	TextToSpeech talker;
	EditText eventmainid;
	Runnable r1;
	LayoutInflater inflater;
	Activity activity;
	String CurrentEventID;
	
	float downX; //initialized at the start of the swipe action
	float upX; //initialized at the end of the swipe action
	
	public AlertMessagePreviewAdapter(Activity activity, String[] title, String[] description,
			String[] reminder_date, String[] event_count_flag, String[] event_id, String[] event_alam_time, String[] event_url, String[] event_package, String[] event_ack_count, String[] eventReminderTime, String[] eventReminderNumber, String[] eventWaitTime, String[] eventNotifyType, ViewPager viewPager) {
		
		this.activity = activity;
		this.context = activity.getApplicationContext();
		this.title = title;
		this.description = description;
		this.reminder_date = reminder_date;
		this.event_count_flag = event_count_flag;
		
		this.event_id = event_id;
		this.event_alam_time = event_alam_time;
		this.event_url = event_url;
		this.event_package = event_package;
		this.event_ack_count = event_ack_count;
		this.eventReminderTime = eventReminderTime;
		this.eventReminderNumber = eventReminderNumber;
		this.eventWaitTime = eventWaitTime;
		this.eventNotifyType = eventNotifyType;
		
		this.viewPager = viewPager;
	}

	
	@Override
	public int getCount() {
		recordCount = title.length;
		return title.length;
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		 Log.v(">>>>>>>>>>>>>>>>################>>>>>>>>>>>>>>>>>",": " + position);
		return parent;   
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == ((RelativeLayout) object);
	}
	
	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		Log.v("****************","instantiateItem");
		// Declare Variables
		TextView txttitle;
		TextView txtdescription;
		TextView txtreminder_date;
		TextView txteventcounter;
		ImageView imgflag;
		EditText eventmainid;
		
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View itemView = inflater.inflate(R.layout.alert_message_preview_item, container, false);
		
		// Locate the TextViews in viewpager_item.xml
		eventmainid  = (EditText) itemView.findViewById(R.id.eventmainid);
		txttitle = (TextView) itemView.findViewById(R.id.title);
		txtdescription = (TextView) itemView.findViewById(R.id.description);
		txtreminder_date = (TextView) itemView.findViewById(R.id.reminder_date);
		txteventcounter = (TextView) itemView.findViewById(R.id.eventcounter);

		// Capture position and set to the TextViews
		eventmainid.setText(event_id[position]);
		txttitle.setText(title[position]);
		txtdescription.setText(description[position]);
		txtreminder_date.setText(reminder_date[position]);
		txteventcounter.setText(event_count_flag[position]);
		
		description[position] = description[position];
		Log.v(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", " : " + description[position]);
		((ViewPager) container).addView(itemView);
		
		try{
			updateEventId = event_alam_time[position];
			String StrEventWaitTime = eventWaitTime[position];
			eventwaittimePeriod = Integer.parseInt(StrEventWaitTime);
		}
		catch(Exception e){
			
		}
		wait_time = eventwaittimePeriod * 1000;
		
		//***********************************************
		
		// Time Zone Of the Current Phone
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
		Date currentLocalTime = calendar.getTime();
		DateFormat date = new SimpleDateFormat("Z");
		Tzone = date.format(currentLocalTime);
		Tzone = " " + Tzone;
		String currentTime = getAddDateTimeStringPreCheck();
		String[] CheckDayTime = currentTime.split(" ");
		DateSendAct = CheckDayTime[0];
		TimeAct = CheckDayTime[1];
		getNativeTimeStamp(DateSendAct, TimeAct, Tzone);
		
		//***********************************************
		
		try{
			// Schedule Events Threads Handling Sounds and Display
		/*	executor = new ScheduledThreadPoolExecutor(1);
			executor1 = new ScheduledThreadPoolExecutor(1);
			
			talker = new TextToSpeech(activity, (OnInitListener) activity);*/
			main_handelr = new Handler();
			
			new CountDownTimer(wait_time, 1000) {
				public void onTick(long millisUntilFinished) {
					//closeExcecutor();
					//Log.v("Timmer Started", "Timmer Started");
				}
				// Remove Alertfrom the screen
				// Set Next Alert
				// Update Backend
				public void onFinish() {
					/*executor.shutdown();
					executor.shutdownNow();
					executor.remove(soundManager);

					executor1.shutdown();
					executor1.shutdownNow();
					executor1.remove(soundManager1);*/
					eventDetailsUpdate();
					setNextReminder();
					activity.finish();
					
				}
			}.start();
		}
		catch(Exception e){
			
		}

		// How many times alert need to be display
		if (reminder_number == 0) {
			reminder_number = 3;
		}
		// Reminder Delay
		if (event_reminder_time == 0) {
			event_reminder_time = 60;
		}
		// Display Reminder
		if (wait_time == 0) {
			// if 0 then default will be 5
			wait_time = 45 * 1000;
		}
		eventTTS = 1;
		eventContPlay = 1;
		eventSoundGap = 1000;
		if (eventSoundGap == 0) {
			eventSoundGap = 5;
		}
	
		
	
		
		itemView.setOnTouchListener(new OnSwipeTouchListener(activity) {
		    public void onSwipeTop() {
		    	
		    	final EditText eventmainid;
				eventmainid = (EditText) itemView.findViewById(R.id.eventmainid);
				CurrentEventID = eventmainid.getText().toString().trim();
		    	Log.v(">>>>>>>>>>>>>>>>>>>>>>>" , "TOP >>>>>>>>>>"  +  CurrentEventID  + " # : "  + recordCount);
		    	/*executor.shutdown();
				executor.shutdownNow();
				executor.remove(soundManager);

				executor1.shutdown();
				executor1.shutdownNow();
				executor1.remove(soundManager1);
				
				if (talker != null) {
        			talker.stop();
        			talker.shutdown();
        		}*/
		    	removeCurrentItem();
		       // Toast.makeText(MyActivity.this, "top", Toast.LENGTH_SHORT).show();
		    }
		    public void onSwipeRight() {
		    	Log.v(">>>>>>>>>>>>>>>>>>>>>>>" , "RIGHT >>>>>>>>>>");
		    	if(readIndex != 0){
		    		readIndex = readIndex + 1;
		    	}
		    	/*executor.shutdown();
				executor.shutdownNow();
				executor.remove(soundManager);

				executor1.shutdown();
				executor1.shutdownNow();
				executor1.remove(soundManager1);
				
				if (talker != null) {
        			talker.stop();
        			talker.shutdown();
        		}*/
		      //  Toast.makeText(MyActivity.this, "right", Toast.LENGTH_SHORT).show();
		    }
		    public void onSwipeLeft() {
		    	Log.v(">>>>>>>>>>>>>>>>>>>>>>>" , "LEFT >>>>>>>>>>");
		    	if(readIndex != 0){
		    		readIndex = readIndex - 1;
		    	}
		    /*	executor.shutdown();
				executor.shutdownNow();
				executor.remove(soundManager);

				executor1.shutdown();
				executor1.shutdownNow();
				executor1.remove(soundManager1);
				
				if (talker != null) {
        			talker.stop();
        			talker.shutdown();
        		}*/
		      //  Toast.makeText(MyActivity.this, "left", Toast.LENGTH_SHORT).show();
		    }
		    public void onSwipeBottom() {
		    	Log.v(">>>>>>>>>>>>>>>>>>>>>>>" , "BOTTOM >>>>>>>>>>"  +  CurrentEventID  + " # : "  + recordCount);
		    	/*executor.shutdown();
				executor.shutdownNow();
				executor.remove(soundManager);

				executor1.shutdown();
				executor1.shutdownNow();
				executor1.remove(soundManager1);
				
				if (talker != null) {
        			talker.stop();
        			talker.shutdown();
        		}*/
		    	removeCurrentItem();

		      // Toast.makeText(MyActivity.this, "bottom", Toast.LENGTH_SHORT).show();
		    }

		public boolean onTouch(View v, MotionEvent event) {
		    return gestureDetector.onTouchEvent(event);
		}
		});
		
		/*soundManager = new SoundManager(position);
		executor.scheduleAtFixedRate(soundManager, 0, 3000, TimeUnit.MILLISECONDS);*/
		return itemView;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		// Remove viewpager_item.xml from ViewPager
		Log.v("****************","destroyItem");
	/*	executor.shutdown();
		executor.shutdownNow();
		executor.remove(soundManager);

		executor1.shutdown();
		executor1.shutdownNow();
		executor1.remove(soundManager1);
		
		if (talker != null) {
			talker.stop();
			talker.shutdown();
		}*/

		((ViewPager) container).removeView((RelativeLayout) object);

	}
	
	class SoundManager implements Runnable {
		
		int index;
		
		public SoundManager(int index) {
			this.index = index;
		}

		int counter = 0;

		@Override
		public void run() {

			if ((counter % 2) == 0) {

				activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
				// our file here is in fact called "soundfile.mp3";

				MediaPlayer player = MediaPlayer.create(activity, R.raw.alarm);
				
				// we start playing the file!
				player.start();

				player.setOnCompletionListener(new OnCompletionListener() {

					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.stop();
						mp.release();

					}
				});

			} else if ((counter % 2) != 0) {
				String text = description[readIndex];
				talker.speak(text, TextToSpeech.QUEUE_FLUSH, null);
			}
			counter++;
		}

	}

	class SoundManager1 implements Runnable {

		@Override
		public void run() {

			activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
			// our file here is in fact called "soundfile.mp3";

			MediaPlayer player = MediaPlayer.create(activity,
					R.raw.alarm);
			// we start playing the file!
			player.start();

			player.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					mp.stop();
					mp.release();
				}
			});
		}

	}
	
	
	//=========================================================================
	
	protected void eventDetailsUpdate() {
		// TODO Auto-generated method stub
		mydb = activity.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor checkPreEventsAckCount = null;

		try {
			String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_ack_count,eventReminderTime,eventReminderNumber,eventWaitTime,eventTimeStamp FROM table_events Where event_alam_time = '" + updateEventId + "'";
			checkPreEventsAckCount = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (checkPreEventsAckCount != null) {
			if (checkPreEventsAckCount.getCount() > 0) {
				while (checkPreEventsAckCount.moveToNext()) {
					ContentValues updateEvetsCount = new ContentValues();
					String updateID = checkPreEventsAckCount.getString(0);
					String event_alam_time = checkPreEventsAckCount.getString(2);
					long event_alam_timecount = Long.parseLong(event_alam_time);

					String updateCounter = checkPreEventsAckCount.getString(3);
					String eventReminderTime = checkPreEventsAckCount.getString(4);
					String eventReminderNumber = checkPreEventsAckCount.getString(5);
					String eventWaitTime = checkPreEventsAckCount.getString(6);
					String eventCurrentTimeStamp = checkPreEventsAckCount.getString(7);

					int eventReminderNumbercount = Integer.parseInt(eventReminderNumber);
					// Event Reminder Time = Time 1
					long eventReminderTimecount = Long.parseLong(eventReminderTime);
					long eventeventWaitTimecount = Long.parseLong(eventWaitTime);
					long eventeventCurrentTimeStamp = Long.parseLong(eventCurrentTimeStamp);

					long curCount = Long.parseLong(updateCounter);
					curCount = curCount + 1;

					long newEventCurrentTimeStamp = (eventReminderTimecount + eventeventWaitTimecount) * curCount;
					newEventCurrentTimeStamp = newEventCurrentTimeStamp + TimeStampValue;
					String newEventCurrentTimeStampStr = String.valueOf(newEventCurrentTimeStamp);

					if (eventReminderNumbercount == curCount) {
						updateEvetsCount.put("event_status", "4");
						updateEvetsCount.put("event_ack_count", curCount);
						updateEvetsCount.put("event_active", "1");
						updateEvetsCount.put("event_alam_time", newEventCurrentTimeStampStr);
						mydb.update(MEM_EVENT, updateEvetsCount, "event_log_id ='" + updateID + "'", null);
					} else {
						nextReminderTimeStamp = newEventCurrentTimeStamp;
						newEventCurrentTimeStampStr = String.valueOf(nextReminderTimeStamp);
						updateEvetsCount.put("event_ack_count", curCount);
						updateEvetsCount.put("event_status", "9");
						updateEvetsCount.put("event_alam_time", newEventCurrentTimeStampStr);
						mydb.update(MEM_EVENT, updateEvetsCount, "event_log_id ='" + updateID + "'", null);
					}

				}
			}
		}
		checkPreEventsAckCount.close();
		mydb.close();

	}
	
	//===========================================================
	
	public long getNativeTimeStamp(String DateSend, String Time, String Tzone) {
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm zzzzz");
		Calendar c = Calendar.getInstance();
		Date d = null;

		try {
			d = ddMMMyyFormat.parse(DateSend.trim() + " " + Time.trim() + Tzone);

		} catch (ParseException e) {
			e.printStackTrace();
		}

		c.setTime(d);

		String date_to_string = ddMMMyyFormat.format(c.getTimeInMillis() / 1000);
		TimeStampValue = c.getTimeInMillis() / 1000;
		return c.getTimeInMillis() / 1000;
	}

	//==========================================================
	
	private String getAddDateTimeStringPreCheck() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}
	
	//==========================================================
	
	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}
	
	//===========================================================
	
	protected void setNextReminder() {
		Bundle bundle = new Bundle();
		EventAlarm alarm1 = new EventAlarm(context, bundle, event_reminder_time);
	}
	
	
	//=============================================================
	private void removeCurrentItem() {
        int position = viewPager.getCurrentItem();
        viewPager.removeViewAt(position);
        this.notifyDataSetChanged();
		updateState();
    }
	
	
	protected void updateState() {
		// TODO Auto-generated method stub
		if(event_id == null || event_id.equals("")){
			
			
		}
		mydb = activity.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor checkPreEvents = null;
		try {
			String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_url,event_package FROM table_events Where event_log_id = '" + CurrentEventID + "'";
			checkPreEvents = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (checkPreEvents != null) {
			if (checkPreEvents.getCount() > 0) {
				while (checkPreEvents.moveToNext()) {
					ContentValues updateEvets = new ContentValues();
					String updateID = checkPreEvents.getString(0);
					eventURL = checkPreEvents.getString(3);
					eventPackage = checkPreEvents.getString(4);
					
					updateEvets.put("event_status", "3");
					updateEvets.put("event_active", "1");
					updateEvets.put("event_update_time", getAddDateTimeString().toString());
					mydb.update(MEM_EVENT, updateEvets, "event_log_id ='" + updateID + "'", null);
				}
			}
			else{
				eventURL = "404";
				eventPackage = "404";
			}
		}
		checkPreEvents.close();
		mydb.close();
		
		Log.v("REQUEST 1:", "VAL PASS 1 :" +eventURL);
		Log.v("REQUEST 2:", "VAL PASS 2 :" +eventPackage);
		
		if (eventPackage.equals("404") && eventURL.equals("404")) {
			closeExcecutor();
			activity.finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		} else if (!eventURL.equals("404")) {
			try {
				Log.e("REQUEST :", "Fire URL**********");
				closeExcecutor();
				
				if(recordCount == 1){
					Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse(eventURL.trim()));
					viewIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
					activity.startActivity(viewIntent);
					activity.finish();
					android.os.Process.killProcess(android.os.Process.myPid());
				}
				else{
					Intent intent = new Intent(context, AlertMessagePreview.class);
					activity.startActivity(intent);
					activity.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
				}
			} catch (Exception e) {

			}
		} else if (!eventPackage.equals("404")) {
			Log.e("REQUEST :", "Fire Package************");
			closeExcecutor();
			if(recordCount == 1){
				Intent i = new Intent(Intent.ACTION_MAIN);
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
				PackageManager managerclock = activity.getPackageManager();
				i = managerclock.getLaunchIntentForPackage(eventPackage.trim());
				i.addCategory(Intent.CATEGORY_LAUNCHER);
				activity.startActivity(i);
				activity.finish();
				android.os.Process.killProcess(android.os.Process.myPid());
			}
			else{
				Intent intent = new Intent(context, AlertMessagePreview.class);
				activity.startActivity(intent);
				activity.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
			}
		}
		else{
			closeExcecutor();
			if(recordCount == 1){
				activity.finish();
				android.os.Process.killProcess(android.os.Process.myPid());
			}
			else{
				Intent intent = new Intent(context, AlertMessagePreview.class);
				activity.startActivity(intent);
				activity.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
			}
		}
	}

	private void closeExcecutor() {
		// TODO Auto-generated method stub
		/*executor.shutdown();
		executor.shutdownNow();
		executor.remove(soundManager);

		executor1.shutdown();
		executor1.shutdownNow();
		executor1.remove(soundManager1);
		
		if (talker != null) {
			talker.stop();
			talker.shutdown();
		}*/
	}

	
	
}







//*************************************************************************************


/*// Media Player handling events
if (eventTTS == 1 && eventContPlay == 1) {
	//counter++;
	soundManager = new SoundManager();
	executor.scheduleAtFixedRate(soundManager, 0, 3000, TimeUnit.MILLISECONDS);
} else if (eventTTS == 1 && eventContPlay == 0) {
	if (AlertMessagePreview.counter == 0) {
		AlertMessagePreview.counter++;
		activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
		// our file here is in fact called "soundfile.mp3";
		MediaPlayer player = MediaPlayer.create(activity , R.raw.alarm);
		// we start playing the file!
		player.start();
		player.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				mp.stop();
				mp.release();
				Handler handler = new Handler();
				final Runnable r = new Runnable() {
					public void run() {
						String text = evtDes;
						talker.speak(text, TextToSpeech.QUEUE_FLUSH, null);
					}
				};
				handler.postDelayed(r, 3000);
			}
		});
	}

} else if (eventTTS == 0 && eventContPlay == 1) {
	soundManager1 = new SoundManager1();
	executor1.scheduleAtFixedRate(soundManager1, 0, 3000, TimeUnit.MILLISECONDS);
} else if (eventTTS == 0 && eventContPlay == 0) {
	if (counter == 0) {
		
		counter++;

		activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
		// our file here is in fact called "soundfile.mp3";

		MediaPlayer player = MediaPlayer.create(activity, R.raw.alarm);
		// we start playing the file!
		player.start();
		
		player.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				mp.stop();
				mp.release();
			}
		});
	}
}*/

